const verificeDao = require('../dao/verifice');

const { verifyJwtToken } = require('../util/server_jwt');

const verificeService = {
    // 验证用户卡密
    async checkCardPassword(cardPassword) {
        // 验证卡密
        let data = await verifyJwtToken(cardPassword);
        if (!data.data) {
            return { code: 401, msg: data.msg };
        }
        try {
            // 查询数据库卡密是否超过次数
            let result = await verificeDao.checkCardPasswordCount(data.data.id);
            if (result.length == 0) {
                return res.json({ code: 401, msg: '卡密疑似伪造' });
            }
            let count = parseInt(result[0].count);
            let maxCount = parseInt(result[0].maxCount);
            // 如果卡密不限制次数的话，就直接返回成功
            if (maxCount == -1) {
                return { code: 200, msg: '卡密验证成功' };
            } else if (count >= maxCount) {
                return res.json({ code: 401, msg: '卡密次数已超过使用限制' });
            } else {
                return { code: 200, msg: '卡密验证成功' };
            }
        } catch (err) {
            return { code: 500, msg: "服务器错误", data: null };
        }
    }
};

module.exports = verificeService;
